package ttot.transitions.plugin

import java.nio.file.Path
import ttot.transitions.api.transition
import java.net.URLClassLoader
import annotation.Annotation

object TransitionFinder {

  def find(basePath: Path, paths: Set[Path]): Set[Class[_]] = {
    val loader = new URLClassLoader(Array(basePath.toUri.toURL), Thread.currentThread().getContextClassLoader)
    paths.map(p => loader.loadClass(classNameFor(basePath, p))).filter(c => hasAnnotation(c, classOf[transition]))
  }

  def hasAnnotation(clazz: Class[_], annotationClass: Class[_]) = {
    clazz.getAnnotations.exists(x => x.annotationType().isAssignableFrom(annotationClass))
  }

  def classNameFor(basePath: Path, path: Path): String = {
    val pathString = basePath.relativize(path).toString
    if (!pathString.endsWith(".class"))
      throw new IllegalArgumentException("Path " + pathString + " does not represent a class file")
    pathString.replace('\\', '.').replace('/', '.').substring(0, pathString.length - 6)
  }

}
